const jsonServer = require("json-server");
const axios = require("axios");
const multer = require("multer");
const server = jsonServer.create();
const router = jsonServer.router("./db.json");
const middlewares = jsonServer.defaults();
const upload = multer({ dest: "uploads" });

// 延迟
const time = (time = 500) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
    }, time);
  });
};
server.use(async (req, res, next) => {
  await time(1500);
  next();
});

// 图片上传
server.post("/photos", upload.single("photo"), async (req, res, next) => {
  const { data } = await axios.post("http://localhost:3000/files", {
    originalname: req.file.originalname,
    filename: req.file.filename,
    path: req.file.path,
    size: req.file.size,
    mimetype: req.file.mimetype
  });
  res.send(data);
});

// 图片服务
server.get("/photos/:id", async (req, res, next) => {
  const id = req.params.id;
  const url = `http://localhost:3000/files/${id}`;
  const { data } = await axios.get(url);
  res.sendFile(data.filename, {
    root: "uploads",
    headers: {
      "Content-type": data.mimetype
    }
  });
});

server.use(middlewares);
server.use(router);

server.listen(3000, () => {
  console.log("JSON Server is running");
});
